import 'dart:async';
import 'dart:math';
import 'dart:ui' as ui;
import 'dart:typed_data';

import 'package:crop_image/crop_image.dart';
import 'package:flutter/material.dart';

import '../../ble/protocol/iledcolor/source/gif/GifDecoder.dart';
import '../loading/LoadingUtil.dart';


class CropPage extends StatefulWidget {
  final Size screenSize;
  final Uint8List imageData;

  const CropPage({super.key, required this.screenSize, required this.imageData});

  @override
  State<CropPage> createState() => _CropPageState();
}

class _CropPageState extends State<CropPage> {
  late CropController controller;

  @override
  void initState() {
    super.initState();
    controller = CropController(
        aspectRatio: widget.screenSize.width / widget.screenSize.height, defaultCrop: const Rect.fromLTRB(0, 0, 1, 1));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color(0xff000000),
        body: SafeArea(
            child: Column(children: [
              Container(
                  padding: const EdgeInsets.only(left: 20, right: 20, top: 10),
                  child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                    _buildBtn(Icons.cancel, onTap: () => Navigator.of(context).pop()),
                    _buildBtn(Icons.check_circle, onTap: () => _finished(context))
                  ])),
              Expanded(
                  child: CropImage(
                      controller: controller,
                      image: Image.memory(widget.imageData),
                      paddingSize: 25.0,
                      alwaysMove: true,
                      minimumImageSize: 50,
                      maximumImageSize: 500)),
              Container(
                  padding: const EdgeInsets.only(left: 20, right: 20, bottom: 20),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [_buildBtn(Icons.rotate_right_outlined, onTap: () => _rotateRight())]))
            ])));
  }

  Widget _buildBtn(IconData icon, {GestureTapCallback? onTap}) {
    return GestureDetector(onTap: onTap, child: Icon(color: Colors.white, icon, size: 40));
  }

  Future<void> _rotateLeft() async => controller.rotateLeft();

  Future<void> _rotateRight() async => controller.rotateRight();

  Future<ui.Image> _rotateAndCropImage(ui.Image image, double angle, Rect cropRect) async {
    final ui.PictureRecorder recorder = ui.PictureRecorder();
    final Canvas canvas = Canvas(recorder);
    final Paint paint = Paint();

    // 计算旋转后的图像尺寸
    final double radians = angle * (pi / 180);
    final double sinTheta = sin(radians);
    final double cosTheta = cos(radians);
    final double rotatedWidth = (image.width * cosTheta + image.height * sinTheta).abs();
    final double rotatedHeight = (image.width * sinTheta + image.height * cosTheta).abs();

    // 移动画布到中心点
    canvas.translate(rotatedWidth / 2, rotatedHeight / 2);

    // 旋转画布
    canvas.rotate(radians);

    // 绘制原始图像
    canvas.drawImageRect(
      image,
      Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble()),
      Rect.fromLTWH(-image.width / 2, -image.height / 2, image.width.toDouble(), image.height.toDouble()),
      paint,
    );

    // 结束录制
    final ui.Picture picture = recorder.endRecording();

    // 将绘制的内容转换为新的 ui.Image
    final ui.Image rotatedImage = await picture.toImage(rotatedWidth.toInt(), rotatedHeight.toInt());

    // 裁剪旋转后的图像
    final ui.PictureRecorder cropRecorder = ui.PictureRecorder();
    final Canvas cropCanvas = Canvas(cropRecorder);

    // 绘制裁剪区域
    cropCanvas.drawImageRect(
      rotatedImage,
      cropRect,
      Rect.fromLTWH(0, 0, cropRect.width, cropRect.height),
      paint,
    );

    // 结束录制
    final ui.Picture cropPicture = cropRecorder.endRecording();

    // 将绘制的内容转换为新的 ui.Image
    final ui.Image croppedImage = await cropPicture.toImage(
      cropRect.width.toInt(),
      cropRect.height.toInt(),
    );

    return croppedImage;
  }

  Future<void> _finished(BuildContext context) async {
    LoadingUtil.showLoading();
    var bytes = widget.imageData;

    if (GifDecoder.isGif(bytes)) {
      // 创建 ImageDecoder
      final ui.Codec codec = await ui.instantiateImageCodec(bytes);

      // 解码 GIF 的每一帧
      final List<ui.Image> frames = [];
      for (int i = 0; i < codec.frameCount; i++) {
        final ui.FrameInfo frameInfo = await codec.getNextFrame();
        frames.add(frameInfo.image);
      }

      Rect rect = controller.cropSize;
      if (controller.rotation.degrees == 90 || controller.rotation.degrees == 270) {
        var v = frames[0].height / frames[0].width;
        rect = Rect.fromLTWH(rect.left * v, rect.top / v, rect.width * v, rect.height / v);
      }
      List<ui.Image> list = [];
      for (var f in frames) {
        ui.Image img = await _rotateAndCropImage(f, controller.rotation.degrees.toDouble(), rect);
        var b = await GifDecoder.resizeImage(img, widget.screenSize);
        list.add(b);
      }

      if (mounted) {
        LoadingUtil.hideLoading();
        Navigator.of(context).pop(list);
      }
    } else {
      final bitmap = await controller.croppedBitmap(maxSize: max(widget.screenSize.height, widget.screenSize.width));
      if (mounted) {
        LoadingUtil.hideLoading();
        Navigator.of(context).pop([bitmap]);
      }
    }
  }
}
